package com.mirror.tk.core.utils;

import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.mirror.tk.core.module.goods.dto.TaobaoGoodsDto;
import com.mirror.tk.framework.utils.mapper.JsonMapper;

/**
 * 商品工具
 */
public class GoodsUtil {

	protected static Logger logger = LogManager.getLogger();
	
	public static final String URL_TPL = "http://pub.alimama.com/items/search.json?q=%s";
	
	private static JsonMapper mapper = JsonMapper.nonEmptyMapper();
	
	// 全局唯一，减少开销
	private static WebClient webClient = new WebClient(BrowserVersion.CHROME);
	static{
		webClient.getOptions().setCssEnabled(false);
		webClient.getOptions().setJavaScriptEnabled(false);
	}
	
	public static TaobaoGoodsDto resolveGoods(String goodsUrl) throws Exception{
		if(StringUtils.isNotBlank(goodsUrl)){
			Page page =  webClient.getPage(String.format(URL_TPL, URLEncoder.encode(goodsUrl, "UTF-8")));
			String data = page.getWebResponse().getContentAsString();
			// 当发现抓取数据受限，暂停1s重试
			if(null == data || data.indexOf("亲，访问受限了") >= 0){
				logger.error("抓取淘宝数据出错了，商品地址：{}，返回数据:{}", goodsUrl, data);
				Thread.sleep(1000);
				logger.debug("重新抓取淘宝数据");
				return resolveGoods(goodsUrl);
			}
			String temp = data.substring(data.indexOf("pageList") + 10, data.indexOf("navigator") - 2);
			List<TaobaoGoodsDto> list = mapper.fromJson(temp, mapper.createCollectionType(List.class, TaobaoGoodsDto.class));
			if(null != list && !list.isEmpty()){
				return list.get(0);
			}
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(resolveGoods("https://item.taobao.com/item.htm?id=537659370987"));
	}
	
}
